package cn.chiship.framework.business.biz.business.controller;

import cn.chiship.framework.business.biz.business.pojo.dto.BusinessOrderPaymentRecordDto;
import cn.chiship.framework.business.biz.business.service.BusinessOrderHeaderService;
import cn.chiship.framework.business.biz.business.service.BusinessOrderPaymentRecordService;
import cn.chiship.framework.business.core.common.XmlUtil;
import cn.chiship.sdk.core.annotation.NoParamsSign;
import cn.chiship.sdk.core.annotation.NoVerificationAppIdAndKey;
import cn.chiship.sdk.core.annotation.NoVerificationProjectId;
import cn.chiship.sdk.core.util.DateUtils;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.framework.util.ServletUtil;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Map;

/**
 * @author lijian
 */
@RestController
@RequestMapping("/pay")
@NoParamsSign
@Api(tags = "支付接口")
public class PayController {
    private static final Logger LOGGER = LoggerFactory.getLogger(PayController.class);

    public static final String SUCCESS = "SUCCESS";

    @Resource
    private BusinessOrderPaymentRecordService businessOrderPaymentRecordService;


    /**
     * 预支付时填写的 notify_url ，支付成功后的回调接口
     *
     * @param request
     */
    @ApiOperation(value = "微信支付成功后的回调接口")
    @PostMapping("/wx/v2/notify")
    @NoVerificationProjectId
    @NoVerificationAppIdAndKey
    public void wxV2Notify(HttpServletRequest request, HttpServletResponse response) {
        try {
            /**
             * 示例数据
             * {
             * 	"transaction_id": "4200000109201805293331420304",
             * 	"nonce_str": "402880e963a9764b0163a979a16e0002",
             * 	"bank_type": "CFT",
             * 	"openid": "oXI6G5Jc4D44y2wixgxE3OPwpDVg",
             * 	"sign": "262978D36A3093ACBE4B55707D6EA7B2",
             * 	"fee_type": "CNY",
             * 	"mch_id": "1491307962",
             * 	"cash_fee": "10",
             * 	"out_trade_no": "14913079622018052909183048768217",
             * 	"appid": "wxa177427bc0e60aab",
             * 	"total_fee": "10",
             * 	"trade_type": "JSAPI",
             * 	"result_code": "SUCCESS",
             * 	"time_end": "20180529091834",
             * 	"is_subscribe": "N",
             * 	"return_code": "SUCCESS"
             * }
             */
            LOGGER.info("===============微信支付回调成功==============");
            Map<String, Object> dataMap = XmlUtil.parseXML(request);
            LOGGER.info("===============微信支付回调参数：==============");
            LOGGER.info(JSON.toJSONString(dataMap));
            String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            response.getWriter().write(data);

            String returnCode = StringUtil.getString(dataMap.get("return_code"));
            String resultCode = StringUtil.getString(dataMap.get("result_code"));
            String outTradeNo = StringUtil.getString(dataMap.get("out_trade_no"));
            BusinessOrderPaymentRecordDto orderPaymentRecordDto = new BusinessOrderPaymentRecordDto();
            orderPaymentRecordDto.setOrderId(outTradeNo);
            if (returnCode.equals(SUCCESS) && resultCode.equals(SUCCESS)) {
                String format = new DecimalFormat("#0.00").format(Double.valueOf(StringUtil.getString(dataMap.get("total_fee"))) / 100);
                BigDecimal totalFee = new BigDecimal(format);
                orderPaymentRecordDto.setTradeNo(StringUtil.getString(dataMap.get("transaction_id")));
                orderPaymentRecordDto.setTradeType(StringUtil.getString(dataMap.get("trade_type")));
                orderPaymentRecordDto.setChannelPayway("wx_v2");
                orderPaymentRecordDto.setTotalFee(totalFee);
                orderPaymentRecordDto.setPayStatus(Byte.valueOf("0"));
                orderPaymentRecordDto.setPartnerId(StringUtil.getString(dataMap.get("mch_id")));
                orderPaymentRecordDto.setUserId(StringUtil.getString(dataMap.get("openid")));
                orderPaymentRecordDto.setPayTime(DateUtils.dateTime("yyyyMMddHHmmss", StringUtil.getString(dataMap.get("time_end"))).getTime());
            } else {
                orderPaymentRecordDto.setPayStatus(Byte.valueOf("1"));
            }
            businessOrderPaymentRecordService.payNotify(orderPaymentRecordDto);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 预支付时填写的 notify_url ，支付成功后的回调接口
     *
     * @param request
     */
    @ApiOperation(value = "微信支付成功后的回调接口")
    @PostMapping("/wx/v3/notify")
    @NoVerificationProjectId
    @NoVerificationAppIdAndKey
    public void wxV3Notify(HttpServletRequest request, HttpServletResponse response) {
        /**
         * {"id":"836f6ad6-6101-5d69-aa28-e76f49a2cb04","create_time":"2023-03-26T20:24:30+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"支付成功","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":"sPxOlJEvr3VXczJG5G0x29udlsBiNQHvp+Z8h92Kef+EIdwPgiRVEXZqeF8QH/9AebFl9UJ7TkeboZbNS/T9vqNhFzM3vankYi0dUrGVZdtb9VhvMamIoV1SaunstoJfBaob+SGlFu5J6r+1erRe565znzzX5a1GJQ7lXU5usPP/+GtMq9yxSj+W+5m+lu7QpQsSQfB0ZrTZcySYmDBxbkSr2yfCjkn2m5MafsRoZGXmifaFe1fJONRqhLq0L6gCUW8xIXXroVh1oN94pgdXR0unTnJyr4/jhkun4oEXpnT0aUtVd93M2Kws8PYZcq1BAyftVSYhfuzgMRDQBgX0/YYxc3Vh1i8fw9EzfgirPpHD0miET/KQzyou6RRLnNvkjNcpwDlF2MbSvxFaAahqdNGenUp8Y2xuMzM0whyFRRBcTVou2kwBAYPg9LpAKD0mafDAML5ZsuFKH6iRiT0kJaq87BYYI1fHbcV6xFm+5svpmiwYVBmdmBw6BqoMG3KIEPVQdtoxE22aLANZWj6+Lz0+WEUDNnxnt2juBX9CR4sUbo8PcY1QYYtUP/ZkO+rUjzs=","associated_data":"transaction","nonce":"W3p0yNPyDok0"}}
         */
        BufferedReader br = null;
        try {
            StringBuilder result = new StringBuilder();
            br = request.getReader();
            for (String line; (line = br.readLine()) != null; ) {
                if (result.length() > 0) {
                    result.append("\n");
                }
                result.append(line);
            }
            LOGGER.info(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @ApiOperation(value = "支付宝支付成功后的回调接口")
    @PostMapping("/ali/notify")
    @NoVerificationProjectId
    @NoVerificationAppIdAndKey
    public void aliPayReturnUrlPost(HttpServletRequest request, HttpServletResponse response) {
        /**
         * https://opendocs.alipay.com/open/194/103296
         */
        /**
         * {
         *   "gmt_create": "2023-03-27 23:04:26",
         *   "charset": "UTF-8",
         *   "seller_email": "services@chiship.cn",
         *   "subject": "打赏",
         *   "sign": "isfXV3o8Ybs3yhLyVVYJoTbpn36ovcC5EmyamLPPs6itwqy7NBv6ppAPjKktPN65ZoDRpAgPe9PSbfrX5TyUhdVhJdQv/O8TQugkMsuSbUYWayyS1F6chpS/6qvPj3ZcMKrRD58N8IonMPElGYYFFrZaHbdSNZ3o++5gOBagB7NpoJLCfJkMEHCFQdAqqEQ9IDDZ5FIsNPYshKVUf5QC1FyxvchU+5e11WDxDKMCWMMbnZCV+7DHyFLApuSQdMEFxDOTdHqhG8wEchTafRg47xW4Eel7cfQg6s1TBqGuqIEKVXtwfRTjj7VeciLnSXfz7rdkQ/BmReuuukLSP52scg==",
         *   "buyer_id": "2088702563173626",
         *   "body": "打赏",
         *   "invoice_amount": "0.10",
         *   "notify_id": "2023032701222230433073621479344934",
         *   "fund_bill_list": "[{\"amount\":\"0.10\",\"fundChannel\":\"ALIPAYACCOUNT\"}]",
         *   "notify_type": "trade_status_sync",
         *   "trade_status": "TRADE_SUCCESS",
         *   "receipt_amount": "0.10",
         *   "buyer_pay_amount": "0.10",
         *   "app_id": "2018081661057690",
         *   "sign_type": "RSA2",
         *   "seller_id": "2088231390225430",
         *   "gmt_payment": "2023-03-27 23:04:33",
         *   "notify_time": "2023-03-27 23:04:33",
         *   "version": "1.0",
         *   "out_trade_no": "20230327_0276_00001",
         *   "total_amount": "0.10",
         *   "trade_no": "2023032722001473621449721322",
         *   "auth_app_id": "2018081661057690",
         *   "buyer_logon_id": "183****3321",
         *   "point_amount": "0.00"
         * }
         */
        try {
            LOGGER.info("===============支付宝支付Post方式回调成功==============");
            Map<String, Object> dataMap = ServletUtil.getParameterValues();
            LOGGER.info("===============支付宝支付Post方式回调成功回调参数：==============");
            LOGGER.info(JSON.toJSONString(dataMap));
            dealAliPayNotify(dataMap, response);
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            out.print("success");
            out.flush();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "支付宝支付成功后的回调接口")
    @GetMapping("/ali/notify")
    @NoVerificationProjectId
    @NoVerificationAppIdAndKey
    public void aliPayReturnUrlGet(HttpServletRequest request, HttpServletResponse response) {
        try {
            LOGGER.info("===============支付宝支付Get方式回调成功==============");
            Map<String, Object> dataMap = ServletUtil.getParameterValues();
            LOGGER.info("===============支付宝支付Get方式回调成功回调参数：==============");
            LOGGER.info(JSON.toJSONString(dataMap));
            dealAliPayNotify(dataMap, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void dealAliPayNotify(Map<String, Object> dataMap, HttpServletResponse response) throws IOException {
        String tradeStatus = StringUtil.getString(dataMap.get("trade_status"));
        String outTradeNo = StringUtil.getString(dataMap.get("out_trade_no"));
        BusinessOrderPaymentRecordDto orderPaymentRecordDto = new BusinessOrderPaymentRecordDto();
        orderPaymentRecordDto.setOrderId(outTradeNo);
        if ("TRADE_SUCCESS".equals(tradeStatus)) {
            String tradeNo = StringUtil.getString(dataMap.get("trade_no"));
            Double totalFree = Double.valueOf(StringUtil.getString(dataMap.get("total_amount")));
            String subject = StringUtil.getString(dataMap.get("subject"));
            //商户号
            String sellerId = StringUtil.getString(dataMap.get("seller_id"));
            //商户账号
            String sellerEmail = StringUtil.getString(dataMap.get("seller_email"));
            //付款号
            String buyerId = StringUtil.getString(dataMap.get("buyer_id"));
            orderPaymentRecordDto.setOrderId(outTradeNo);
            orderPaymentRecordDto.setTradeNo(tradeNo);
            orderPaymentRecordDto.setTradeType("zfb");
            orderPaymentRecordDto.setChannelPayway("zfb");
            orderPaymentRecordDto.setTotalFee(BigDecimal.valueOf(totalFree));
            orderPaymentRecordDto.setPayStatus(Byte.valueOf("0"));

            //商户号
            orderPaymentRecordDto.setPartnerId(sellerId);
            orderPaymentRecordDto.setAccount(sellerEmail);
            orderPaymentRecordDto.setUserId(buyerId);
            orderPaymentRecordDto.setPayTime(DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", StringUtil.getString(dataMap.get("gmt_payment"))).getTime());
            orderPaymentRecordDto.setSubject(subject);
        } else {
            orderPaymentRecordDto.setPayStatus(Byte.valueOf("1"));
        }
        businessOrderPaymentRecordService.payNotify(orderPaymentRecordDto);
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.print("success");
        out.flush();
    }
}